package com.mk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.service.impl.BaseService;
import com.mk.common.BeanCopier;
import com.mk.common.Config;
import com.mk.mapper.UserMapper;
import com.mk.model.entity.Org;
import com.mk.model.entity.Role;
import com.mk.model.entity.User;
import com.mk.model.request.UserRequest;
import com.mk.service.IOrgService;
import com.mk.service.IRoleService;
import com.mk.service.IUserRoleService;
import com.mk.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 4:12 PM 3/13/18
 */
@Service
public class UserService extends BaseService<UserMapper,User> implements IUserService {

    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IOrgService orgService;

    @Override
    public User saveUser(UserRequest request) {
        if(request == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请传入添加的用户信息");
        //用户名 密码 姓名 性别以及部门不可为空
        if(StringUtils.isEmpty(request.getUsername()) || StringUtils.isEmpty(request.getPassword())
                || request.getOrgId() == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"添加用户时用户名、密码以及部门不可为空");
        User existByUsername = get(request.getUsername());
        //用户名不可重复
        if(existByUsername != null)
            throw new ApplicationException(StatusCode.UNIQUE_KE.getCode(),"用户名已存在");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        User user = BeanCopier.copy(request,User.class);
        user.setPassword(encoder.encode(request.getPassword()));//给密码加密
        Date nowDate = new Date();
        user.setCreateTime(nowDate);
        user.setUpdateTime(nowDate);
        if(super.insert(user)) {
            if(!CollectionUtils.isEmpty(request.getRoleIds())){
                userRoleService.changeUserRole(user.getId(),request.getRoleIds());
            }
            return user;
        }else
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"添加用户失败");
    }

    @Override
    public Boolean updateUser(UserRequest request) {
        if(request == null || request.getId() == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请选择编辑的用户信息");
        User exist = get(request.getId());//查询该id对应的数据是否存在
        if (exist == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"编辑的用户信息不存在");
        if(!StringUtils.isEmpty(request.getUsername())){
            exist = get(request.getUsername());
            //用户名判重
            if(exist != null && !exist.getId().equals(request.getId()))
                throw new ApplicationException(StatusCode.UNIQUE_KE.getCode(),"编辑的用户名已存在");
        }
        exist = BeanCopier.copy(request,User.class);
        exist.setUpdateTime(new Date());
        if(!CollectionUtils.isEmpty(request.getRoleIds())){
            userRoleService.changeUserRole(exist.getId(),request.getRoleIds());
        }
        return super.updateById(exist);
    }

    @Override
    public Boolean deleteUser(Long id) {
        if(id == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请选择删除的用户信息");
        User exist = get(id);
        if(exist == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"删除的用户不存在");
        if("admin".equals(exist.getUsername()))
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"超级管理员不可删除");
        //todo 判断用户在其他地方使用
        exist.setUpdateTime(new Date());
        exist.setIsDeleted(Config.ABLE_CONFIG.UNABLE);
        return super.updateById(exist);
    }

    @Override
    public Boolean modifyPassword(UserRequest request) {
        if(request == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请传入需要修改的密码信息");
        if(request.getId() == null
                || StringUtils.isEmpty(request.getPassword()))
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"修改密码时请传入新密码");
        User existById = get(request.getId());
        if(existById == null)
            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"修改密码的用户信息不存在");
        if(!StringUtils.isEmpty(request.getUsername())){
            User existByUsername = get(request.getUsername());
            if(existByUsername != null && existByUsername.getId() != request.getId())
                throw new ApplicationException(StatusCode.UNIQUE_KE.getCode(),"用户名已存在");
        }
        User user = BeanCopier.copy(request,User.class);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        if(!request.getOldPassword().equals(existById.getPassword())) {
        //传原密码去验证
        if(!StringUtils.isEmpty(request.getOldPassword())){
            if(!encoder.matches(request.getOldPassword(),existById.getPassword()))
                throw new ApplicationException(StatusCode.CONFLICT.getCode(), "修改密码时输入的旧密码有误");
        }
        user.setPassword(encoder.encode(request.getPassword()));
        user.setUpdateTime(new Date());
        return super.updateById(user);
    }

    @Override
    public User get(Long id) {
        User user = super.selectById(id);
        if(user != null){
            if(user.getOrgId() != null) {
                Org org = orgService.get(user.getOrgId());
                user.setOrgName(org.getTitle());
            }
            List<Role> roles = roleService.findByUserId(id);
            if(!CollectionUtils.isEmpty(roles)){
                Role role = roles.get(0);
                user.setRoleId(role.getId());
                user.setRoleName(role.getName());
            }
        }
        return user;
    }

    @Override
    public User get(String username) {
        return super.selectOne(new EntityWrapper<User>()
                .eq("username",username)
                .eq(Config.ABLE_CONFIG.ABLE_COLUMN,Config.ABLE_CONFIG.ABLE));
    }

    @Override
    public Page<User> getPage(UserRequest request, Page<User> page) {
        if(request == null)
            request = new UserRequest();
        request.setIsDeleted(Config.ABLE_CONFIG.ABLE);
        List<User> users = baseMapper.getPage(page,request);
        page.setRecords(users);
        return page;
    }

    @Override
    public Boolean orgCanDel(Long orgId) {
        List<User> users = super.selectList(new EntityWrapper<User>()
                .eq("org_id",orgId)
                .eq(Config.ABLE_CONFIG.ABLE_COLUMN,Config.ABLE_CONFIG.ABLE));
        return CollectionUtils.isEmpty(users);
    }
}
